<?php
namespace ac\component\aliyun;

use Yii;
use OSS\OssClient;
use OSS\Core\OssException;

/*
阿里云 Oss类
*/
class Oss extends Ali
{

    public $accessKeyId;
    public $accessKeySecret;
    public $endpoint;
    public $bucket;

    public function __construct($accessKeyId, $accessKeySecret, $endpoint, $bucket)
    {
        $this->accessKeyId = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
        $this->endpoint = $endpoint;
        $this->bucket = $bucket;
    }

    /*创建存储空间*/
    public function createBucket()
    {
        try{
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            $res = $ossClient->createBucket($this->bucket);
            // P($res);
            if($res['info']['http_code'] == 200){
                return true;
            }
        }catch(OssException $e) {
            print $e->getMessage();
        }
        return false;
    }

    /*
    上传文件
    $object     文件名称
    $filePath   由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt
    */
    public function uploadFile($object, $filePath)
    {
        $options = array(
            OssClient::OSS_HEADERS => array(
                'x-oss-object-acl' => 'private',
                'x-oss-meta-info' => 'your info'
            ),
        );
        try{
            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
            $res = $ossClient->uploadFile($this->bucket, $object, $filePath);
            P($res);
            if($res['info']['http_code'] == 200){
                return true;
            }
        }catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        return false;
    }



}